<template>
    <div>
        <el-card shadow="never" class="!border-none">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="个人中心" name="center">
                    <el-form class="mx-auto mt-4" style="max-width: 680px" :model="form" label-suffix='：'
                        :label-position="labelPosition" label-width="120px" size="large">

                        <el-form-item prop="username" class="!mb-8" label="用户昵称">
                            <el-input v-model="user.username" type="text" autocomplete="off" placeholder="请输入用户昵称"
                                disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="account" class="!mb-8" label="登陆账号">
                            <el-input v-model="user.account" type="text" autocomplete="off" placeholder="请输入登陆账号"
                                disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="phone" class="!mb-8" label="手机号">
                            <el-input v-model="user.phone" type="text" autocomplete="off" placeholder="请输入手机号" disabled>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="roleId" class="!mb-8" label="所属角色">
                            <el-select v-model="role" placeholder="请选择所属角色" clearable disabled>
                                <el-option v-for="(item, index) in user.role" :label="item" :value="index" />
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="status" class="!mb-8" label="状态">
                            <el-switch inline-prompt v-model="user.status" active-text="启用" inactive-text="停用" disabled
                                :active-value="1" :inactive-value="0" />
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="设置" name="setting">
                    <el-form class="mx-auto mt-4" ref="formRef" style="max-width: 680px" :model="form" :rules="rules"
                        label-suffix='：' :label-position="labelPosition" label-width="120px" size="large">
                        <el-form-item prop="oldPassword" label="旧密码">
                            <el-input v-model="form.oldPassword" type="password" autocomplete="off" placeholder="请输入旧密码"
                                show-password>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="password" label="新密码">
                            <el-input v-model="form.password" type="password" autocomplete="off" placeholder="请输入新密码"
                                show-password>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="confirmPassword" label="确认密码">
                            <el-input v-model="form.confirmPassword" type="password" autocomplete="off"
                                placeholder="请再次输入新密码" show-password>
                            </el-input>

                        </el-form-item>
                        <el-form-item class="custom " label=" ">
                            <div class="sm:mt-6">
                                <el-button type="primary" @click="submitForm(formRef)" :loading="flag">
                                    确认
                                </el-button>
                                <el-popconfirm ref="popconfirmRef" @confirm="resetForm(formRef)" @cancel="cancelEvent"
                                    confirm-button-text="确认" cancel-button-text="取消" class="box-item" title="确认重置表单?"
                                    placement="top-start">
                                    <template #reference>
                                        <el-button>
                                            重置
                                        </el-button></template>
                                </el-popconfirm>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { getUserByAccount, updatePassword } from '@/api/user'
import { ElMessage, type FormInstance, type TabsPaneContext } from 'element-plus'

import { useRoute } from 'vue-router';

import { settingMode } from "@/stores/setting";
const settingsStore = settingMode()
const screenWidth = computed(() => {
    return settingsStore.screenWidth
})

const route = useRoute();
const data = ref(null)
const role = ref('admin')
const flag = ref(false)
const formRef = ref<FormInstance>()
const activeName = ref('center')



const loading = ref(false)


const labelPosition = computed(() => {
    return screenWidth.value < 768 ? 'top' : 'right'
})
const user = ref({
    id: null,
    account: null,
    username: null,
    phone: null,
    role: ['admin'],
    status: 1,
    roleNickname: null
})
const form = ref({
    password: null,
    oldPassword: null,
    confirmPassword: null
})
const validateIdentical = (rule: any, value: string, callback: any) => {
    if (value !== form.value.password) {
        callback(new Error('密码不一致'))
    } else {
        callback()
    }

}

const rules = ref({
    oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 8, max: 16, message: '长度在 8 - 16 位, 至少8位以上', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, max: 16, message: '长度在 8 - 16 位, 至少8位以上', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        { min: 8, max: 16, message: '长度在 8 - 16 位, 至少8位以上', trigger: 'blur' },
        { validator: validateIdentical, trigger: 'blur' }
    ],
})
const getUserData = async () => {
    loading.value = false
    const params = JSON.parse(localStorage.getItem('user') || '{}')

    const res = await getUserByAccount(params)

    user.value = res.data

    // form.value = res.data.user

    loading.value = true

}

const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

const submitForm = async (formEl: FormInstance | undefined) => {
    console.log(form.value)
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            try {
                flag.value = true
                const res = await updatePassword(form.value)

                if (res.code == 200) flag.value = false
                ElMessage.success('更新成功')
                formEl.resetFields()
            } catch (error) {
                console.log(error)
                flag.value = false
            }

        } else {

            console.log('error submit!')
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const cancelEvent = () => {
    console.log('cancel!')
}

watch(() => route.query.activeName, (val) => {
    if (val) {
        activeName.value = val as string;
    }
}, { immediate: true })

</script>

<style scoped>
:deep(.custom .el-form-item__label) {
    opacity: 0;
}

:deep(.el-input-group__append) {
    cursor: pointer;
}

:deep(.el-input-group__append:active) {
    background-color: #eee;
}
</style>